import DEFINE = require('./../../common/DEFINE');
import GCJ_CLASS_TYPE = require('./../../common/GCJ_CLASS_TYPE');
import Serializer = require('./../base/Serializer');
import ObjPosition = require('./../base/ObjPosition');
import GroupObj = require('./../obj/GroupObj');
import SJGPage = require('./../cont/SJGPage');
import Parser = require('./../base/Parser');
import GlobalData = require('./../../z/GlobalData');
var async  = require( 'async'); // 同步控制
var fs = require('fs')
var CONFIG=require('../../../../common/config');

export  = SJGDocumentBody;

/**
 *
 * @author 
 *
 */
class SJGDocumentBody extends Serializer{
    public pos: ObjPosition = new ObjPosition();// 模版的尺寸
    public background: GroupObj = null;
    public pages: Array<SJGPage> = new Array<SJGPage>(); // 页面数组
	public constructor(g?) {
        super(g);
        this.ct = GCJ_CLASS_TYPE.CLASS_TYPE_SJGDocumentBody;
	}
	
	
    // 从json对象(注意不是json字符串)中解析
    public fromJson(jsonObj, versionId) { 
        super.fromJson( jsonObj, versionId );
        
        this.pos = Parser.fromUnknownJson( jsonObj.pos, versionId );
        this.background = Parser.fromUnknownJson( jsonObj.background, versionId );
        if(jsonObj.pages){
            for ( var i = 0; i < jsonObj.pages.length;i++)
            {
//             if(i!=2) continue; // for test
                
                // 为兼容nodejs代码，传递全局域
                var one: SJGPage = Parser.fromUnknownJson( jsonObj.pages[i], versionId , this.getGlobalData());
                if(one){
                    this.pages.push( one );
                }
                
//                one.upgradeData();// 升级数据for test
            }
        }
       
    }
    // 转成json字符串
    public toJson(withPages:boolean = true):string {
        // 去掉父json字符串的头尾
        var superJson = super.toJson();
        superJson = superJson.substr(1,superJson.length-2);

        // BEGIN
        var ret = '{';
        ret +=superJson;
        // pos
        ret += ',';
        ret += '"pos":'
        ret += this.pos.toJson();
        
        // background
        if(this.background){
            ret += ',';
            ret += this.background.toJson();           
        }
        
        // pages
        ret += ',';
        ret += '"pages":'
        ret += '[';
        if (withPages) {// 是否处理page信息
            for ( var i = 0; i < this.pages.length;i++){
                if(i>0){
                    ret += ',';
                }
                ret += this.pages[i].toJson();
            }
        }
        ret += ']';

        // END
        ret += "}";
        return ret;
    }
    // 转成json字符串(仅pages)
    public toJsonPages():string {
        var ret = '[';
        for ( var i = 0; i < this.pages.length;i++){
            if(i>0){
                ret += ',';
            }
            ret += '{"pageData":"' + this.pages[i].toJson().replace(/\"/g,'\\"') + '"';
            ret += ',"replaces":"' + this.pages[i].toJsonReplaces().replace(/\"/g,'\\"') + '"';
            ret += ',"page_id":"' + (this.pages[i].describe.page_id || 0) + '"';            // 模版页id
            ret += ',"base_page_id":"' + (this.pages[i].describe.base_page_id || 0) + '"';   // 母版页id
            ret += ',"page_index":' + this.pages[i].describe.index;
            ret += ',"backup_flg":' + this.pages[i].describe.backup_flg;
            ret += ',"rep_hash_tag":' + this.pages[i].getReplaceObjTag() + '}';
        }
        ret += ']';
        return ret;
    }

    // 新建空白Page
    // 参数：［可选］如果不传入，则添加到末尾
    // 参数：［可选］pageJson页面json
    // 参数：［可选］mstPageId 母版page_id
    // 返回：新增页的id
    public addPage(pageIndex?: number,pageJson?: string,mstPageId?: number):number{
        var newPage: SJGPage=null;
        if(pageJson){
            var pageJsonObj: Object=JSON.parse(pageJson);
            var page:SJGPage=new SJGPage(this.getGlobalData());// 为兼容nodejs代码，传递全局域
            page.fromJson(pageJsonObj,0);
            newPage=page.copyPage();
            newPage.upgradeData();
            newPage.describe.base_page_id=mstPageId;
        }else{
            newPage =new SJGPage(this.getGlobalData());// 为兼容nodejs代码，传递全局域
            newPage.root.pos.w=DEFINE.DEFAULT_TEMPLATE_PAGE_WITH;
            newPage.root.pos.h=DEFINE.DEFAULT_TEMPLATE_PAGE_HEIGHT;
            newPage.describe.id=this.getGlobalData().idGenerator().newId();// 分配id
            newPage.describe.index=this.pages.length;            
        }
        
        if ( typeof pageIndex=="number" && pageIndex >= 0 && pageIndex <= this.pages.length ){
            this.pages.splice( pageIndex, 0, newPage );
            // 更新后续的index
            for ( var i = pageIndex; i < this.pages.length;i++){ 
                var one: SJGPage = this.pages[i];
                one.describe.index = i;
            }
        } else { 
            
            this.pages.push( newPage );
        }
        
        return newPage.describe.id;
    }
    // 删除页
    // 参数：pageIndex页偏移，注意：不是id
    public deletePage(pageIndex:number){
        this.pages.splice( pageIndex, 1);
        // 更新后续的index
        for ( var i = pageIndex; i < this.pages.length;i++){ 
            var one: SJGPage = this.pages[i];
            one.describe.index = i;
        }
    }
    // 根据id取得page
    public getPageById(pageId:number):SJGPage{
        // 更新后续的index
        for ( var i = 0; i < this.pages.length;i++){ 
            var one: SJGPage = this.pages[i];
            if(one.describe.id == pageId){
                return one;
            }
        }
        return null;
    }
    // 增加测试页
    public addTestData(){
        // 添加1页
        var page:SJGPage = this.getPageById(this.addPage());
        
        page.addTestData();
    }
    //  升级数据，需要升级到接口实现
    public upgradeData() {
        for(var i=0;i<this.pages.length;i++) {
            var one: SJGPage=this.pages[i];
            if(one) {
                one.upgradeData();
            }
        }
    }
    
    
    
//SJG_MARK_APPEND--------------------
    // 初始化用户的可替换数组
    public initUserReplaces(jsonObj, versionId){
        // 根据用户的可替换数组，对页面进行增、删、改

        // 如果用户数据某一页没有可替换数组，则将page的thumbUrl替换为模版页的缩略图到url
        // 如果用户数据某一页有可替换数组，则page的thumbUrl设置为null，并设置page的userReplaces


        for (var i in this.pages) {
            var page:SJGPage = this.pages[i];
            var replaces = jsonObj[i];

            if(page){
                page.initUserReplaces(replaces,versionId);
            }
        }
    }
    // 增加用户的可替换数组－只有基本属性
    public addTestDataOfUserReplaces(){
        for (var page in this.pages) {
            this.pages[page].addTestDataOfUserReplaces();
        }
    }
    // 排版
    public typeset(callback:Function){

        // 如果需要生成缩略图，则组成async能识别的函数数组
        var asyncFuncs = [];
        for (var page in this.pages) {
            asyncFuncs.push((function (op) {
                return function (asyncCallback) {  // asyncCallback(null, 'one');// asyncCallback(null, 'two');
                    op.typeset(asyncCallback);
                }
            })(this.pages[page])); // 利用闭包解决动态参数传递问题
        }
        async.parallel(asyncFuncs, function (err, results) {
            callback();
        });



    }

}//SJG_MARK_END-------------------------